﻿/****************************************************************************************************************
*                                                                                                               *
* Copyright (C) 2011 5173.com                                                                                   *
* This project may be copied only under the terms of the Apache License 2.0.                                    *
* Please visit the project Home Page http://bqqapicsharp.codeplex.com/ for more detail.                         *
*                                                                                                               *
****************************************************************************************************************/

namespace BQQAPIClient.Core.Protocol
{
    using System;
    using System.Collections.Generic;
    using BQQAPIClient.Core.Utility;

    internal class TLVList : List<TLV> {}

    internal struct TLV
    {
        internal byte[] v;
        internal byte t;
        internal ushort l;

        internal ushort Length
        {
            get
            {
                return (ushort)(sizeof(ushort) + v.Length + 1);
            }
        }

        internal TLV(byte t, byte[] v) : this()
        {
            this.t = t;
            this.v = v;
            l = (ushort)((v == null) ? 0 : v.Length);
        }

        internal TLV(byte t, byte v)
            : this(t, new byte[] { v })
        {
        }

        internal static TLV GetTLV(byte[] data, ref int index)
        {
            var tlv = new TLV();
            tlv.t = data[index];
            index++;
            tlv.l = data.GetLittleEndianUInt16(index);
            index += sizeof(ushort);
            var bytes = new byte[tlv.l];
            Buffer.BlockCopy(data, index, bytes, 0, bytes.Length);
            index += bytes.Length;
            tlv.v = bytes;
            return tlv;
        }

        internal byte[] GetBytes()
        {
            List<byte> bytes = new List<byte>();
            bytes.Add(t);
            bytes.AddRange(l.GetBigEndianBytes());
            bytes.AddRange(v);
            return bytes.ToArray();
        }
    }
}
